﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using StateGrid.User;
using StateGrid;

public abstract partial class ListItemBasePage : StateGrid.CommonPage
{
    // 子类中实现以下函数
    
    /// <summary>
    /// 在最开始的时候调用，完成子类的初始化过程
    /// </summary>
    protected abstract void DoInit();
    
    /// <summary>
    /// 设置要显示的字段
    /// </summary>
    protected abstract void SetItemFields();
    
    /// <summary>
    /// 获得记录总数
    /// </summary>
    /// <returns>记录总数</returns>
    protected abstract int GetItemCount();
    
    /// <summary>
    /// 获得需要显示的记录
    /// </summary>
    /// <param name="begin">起始记录号</param>
    /// <param name="end">终止记录号</param>
    /// <returns>数据源</returns>
    protected abstract Object GetItemSource(int begin, int end);
    
    /// <summary>
    /// 是否显示删除按钮
    /// </summary>
    /// <returns></returns>
    protected abstract Boolean HasDeleteField();
    
    // 在删除按钮生效时被调用，删除失败时返回false。message中返回失败信息。
    protected abstract bool OnDelete(DataKey dataKey, out string message);


    // 以下是子类中使用的辅助函数，用于方便子类实现。

    /// <summary>
    /// 在SetItemField()中使用，注册用以标识记录的域
    /// </summary>
    /// <param name="fields">被当作primary key的域</param>
    protected void RegisterKeyField(params string[] fields)
    {
        itemGridView.DataKeyNames = fields;
    }
    
    /// <summary>
    /// 在SetItemFields()中使用，添加一个普通列
    /// </summary>
    /// <param name="header">head标题</param>
    /// <param name="field">绑定字段</param>
    /// <param name="length">字段显示长度</param>
    ///  <param name="percentage">列宽百分比</param>
    protected void AddBoudField(string header, string field, int length, int percentage)
    {
        BoundField boundField = new BoundField();
        boundField.HeaderText = header;
        boundField.DataField = field;
        this.itemGridView.Columns.Add(boundField);

        int index=this.itemGridView.Columns.IndexOf(boundField);

        this.itemGridView.Columns[index].HeaderStyle.Width = Unit.Percentage(percentage) ;

        if (length > 0)
        {
            length = length < 3 ? 3: length;
            fieldMaxLength.Add(index,length);
        }
    }

    /// <summary>
    /// 在SetItemFields()中使用，添加一个链接列
    /// </summary>
    /// <param name="header">head标题</param>
    /// <param name="format">url格式字符串</param>
    /// <param name="fields">格式字符中引用的列</param>
    protected void AddHyperLinkField(string header, string format, string[] fields)
    {
        HyperLinkField hyperlinkField = new HyperLinkField();
        hyperlinkField.HeaderText = header;
        hyperlinkField.Text = header;
        hyperlinkField.DataNavigateUrlFields = fields;
        hyperlinkField.DataNavigateUrlFormatString = format;
        this.itemGridView.Columns.Add(hyperlinkField);
    }

    /// <summary>
    /// 在SetItemFields()中使用，添加一个链接列
    /// </summary>
    /// <param name="header">head标题</param>
    /// <param name="format">url格式字符串</param>
    /// <param name="fields">格式字符中引用的列</param>
    /// <param name="target">链接的目的如（_blank,_parent,_self等)</param>
    protected void AddHyperLinkField(string header, string format, string[] fields,String target)
    {
        HyperLinkField hyperlinkField = new HyperLinkField();
        hyperlinkField.HeaderText = header;
        hyperlinkField.Text = header;
        hyperlinkField.DataNavigateUrlFields = fields;
        hyperlinkField.DataNavigateUrlFormatString = format;
        hyperlinkField.Target = target;

        this.itemGridView.Columns.Add(hyperlinkField);
    }

    ///<summary>添加替代连接</summary>
    ///<param name="header">header标题</param>
    ///<param name="field">显示字段</param>
    ///<param name="url">url链接</param>
    ///<param name="parms">链接字段</param>
    protected void AddHyperLinkField(string header, string field, string url, string[] parms)
    {
        HyperLinkField hlField = new HyperLinkField();
        hlField.HeaderText = header;
        hlField.DataTextField = field;
        hlField.DataNavigateUrlFields = parms;
        hlField.DataNavigateUrlFormatString = url;

        this.itemGridView.Columns.Add(hlField);
    }

    // MasterPage中控件的引用
    private GridView itemGridView;
    private HyperLink headPageHyperLink;
    private HyperLink prevPageHyperLink;
    private HyperLink nextPageHyperLink;
    private HyperLink tailPageHyperLink;
    private Label pageInfoLabel;
    private TextBox pageNumberTextBox;
    private Button submitButton;

    // 基础信息
    private int page = 0;

    private int pageSize = 20;
    private int totalItemCount = 0;
    private int totalPageCount = 0;

    // 显示相关
    private int deleteFieldIndex = 0;
    private Dictionary<int, int> fieldMaxLength = new Dictionary<int,int>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsLogIn())
        {
            return;
        }
        // 调用子类的初始化方法
        DoInit();

        // 初始化控件相关内容
        InitControls();

        // 刷新控件的内容
        if (!IsPostBack)
            RefreshContents();
    }

    /// <summary>
    /// 判断用户是否登录
    /// </summary>
    private bool IsLogIn()
    {
        bool flag = true;
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            flag = false;
        }
        return flag;
    }

    private void InitControls()
    {
        itemGridView = this.Master.FindControl("itemGridView") as GridView;
        headPageHyperLink = this.Master.FindControl("headPageHyperLink") as HyperLink;
        prevPageHyperLink = this.Master.FindControl("prevPageHyperLink") as HyperLink;
        nextPageHyperLink = this.Master.FindControl("nextPageHyperLink") as HyperLink;
        tailPageHyperLink = this.Master.FindControl("tailPageHyperLink") as HyperLink;

        pageInfoLabel = this.Master.FindControl("pageInfoLabel") as Label;
        pageNumberTextBox = this.Master.FindControl("pageNumberTextBox") as TextBox;
        submitButton = this.Master.FindControl("submitButton") as Button;
        if (HasDeleteField())
        {
            itemGridView.RowDeleting += new GridViewDeleteEventHandler(ItemGridView_RowDeleting);
            itemGridView.RowDataBound += new GridViewRowEventHandler(ItemGridView_RowDataBound);
        }
        this.submitButton.Click += new EventHandler(SubmitButton_Click);
    }

    /// <summary>
    /// 刷新显示内容
    /// </summary>
    protected void RefreshContents()
    {
        ReloadData();
        RefreshGridView();
        RefreshBarArea();
    }

    private void ReloadData()
    {
        page = ParseIntegerQuery("page");

        totalItemCount = GetItemCount();
        totalPageCount = (totalItemCount + pageSize - 1) / pageSize;

        if (page < 0)
            page = 0;
        if (page >= totalPageCount)
            page = totalPageCount - 1;
    }

    private void RefreshGridView()
    {
        itemGridView.AutoGenerateColumns = false;
        itemGridView.Columns.Clear();
        fieldMaxLength.Clear();
        SetItemFields(); // 调用子类的方法
        itemGridView.DataSource = GetItemSource(page * pageSize+1, (page + 1) * pageSize);

        //获取是否要显示删除按钮
        if (HasDeleteField())
        {
            ButtonField deleteField = new ButtonField();
            deleteField.HeaderText = "删除";
            deleteField.Text = "删除";
            deleteField.CommandName = "Delete";
            deleteField.ButtonType = ButtonType.Link;
            itemGridView.Columns.Add(deleteField);
            deleteFieldIndex = itemGridView.Columns.IndexOf(deleteField);
        }
        
        
        itemGridView.DataBind();
    }

    private void RefreshBarArea()
    {
        this.headPageHyperLink.NavigateUrl = BuildPagingURL(0);
        this.tailPageHyperLink.NavigateUrl = BuildPagingURL(totalPageCount - 1);

        if (page != 0)
            this.prevPageHyperLink.NavigateUrl = BuildPagingURL(page - 1);
        else
            this.prevPageHyperLink.Enabled = false;

        if (page < (totalPageCount - 1))
            this.nextPageHyperLink.NavigateUrl = BuildPagingURL(page + 1);
        else
            this.nextPageHyperLink.Enabled = false;

        this.pageInfoLabel.Text =
            String.Format("{0}/{1}&nbsp;&nbsp;共{2}条记录", page + 1, totalPageCount, totalItemCount);

       
    }

    private string BuildPagingURL(int pageNumber)
    {
        return BuildURL(Request.RawUrl,
                        "page", pageNumber.ToString());
    }

    private void ItemGridView_RowDeleting(Object sender, GridViewDeleteEventArgs e)
    {
        string message = "";
        bool ret = OnDelete(this.itemGridView.DataKeys[e.RowIndex], out message);
        e.Cancel = !ret;

        if (message != "")
            Response.Write("<Script type='text/javascript'>alert('" + message + "')</Script>");

        RefreshContents();
    }

    private void ItemGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[deleteFieldIndex].Attributes.Add("onclick", "return window.confirm( '你确认删除吗? '); ");

            foreach (KeyValuePair<int, int> pair in fieldMaxLength)
            {
                int index = pair.Key;
                int length = pair.Value;

                string text = e.Row.Cells[index].Text;
                if (text.Length > length)
                    e.Row.Cells[index].Text = text.Substring(0, length - 3) + "...";
            }
        }
    }

    private void SubmitButton_Click(Object sender, EventArgs e)
    {
        int pageNumber;
        try
        {
            pageNumber = Int32.Parse(this.pageNumberTextBox.Text.Trim());
        }
        catch (Exception)
        {
            Response.Write("<Script>alert('请输入正确的页码')</Script>");
            return;
        }

        Response.Redirect(BuildPagingURL(pageNumber - 1));
    }
}